using System;
using System.Threading;
using System.Collections.Generic;
using OpenMetaverse;

namespace OpenFuse.Backend.Commands
{
	public class GetChildrenCommand : Command
	{
		public delegate void Result(SlSession session, Cache.Node parentNode, List<Cache.Node> nodes);

		Result _resultCallback;
		Cache.FolderNode _parent;
		
		public GetChildrenCommand(SlSession session, Cache.FolderNode parent, Result resultCallback) : base(session)
		{
			_parent = parent;
			_resultCallback = resultCallback;
		}

		public override void Run()
		{
			_session.Logger.Debug("Start GetChildrenCommand " + _parent.MangledPath);
				
			if(_session.GridClient.Network.Connected)
			{
				List<Cache.Node> result = new List<Cache.Node>();

				// Get the folder contents from the inventory server
				List<InventoryBase> folderContents = _session.GridClient.Inventory.FolderContents(new UUID(_parent.Id), _session.AvatarId, true, true, OpenMetaverse.InventorySortOrder.ByName, 40000);
				if(folderContents != null)
				{
					foreach(InventoryBase e in folderContents)
					{
						Cache.Node newNode = null;

						if(e is OpenMetaverse.InventoryFolder)
						{
							OpenMetaverse.InventoryFolder f = (OpenMetaverse.InventoryFolder)e;
							newNode = _session.Cache.Nodes.GetById(f.UUID.Guid);
							if(newNode == null)
								newNode = new Cache.FolderNode(f.UUID.Guid, f.Name, f.ParentUUID.Guid, f.Version);
						}
						else if(e is OpenMetaverse.InventoryItem)
						{
							//TODO handle asset id of files
							OpenMetaverse.InventoryItem i = (OpenMetaverse.InventoryItem)e;
							
							newNode = _session.Cache.Nodes.GetById(i.UUID.Guid);
							if(newNode == null)
								newNode = new Cache.FileNode(i.UUID.Guid, i.Name, i.ParentUUID.Guid, i.AssetUUID.Guid, i.AssetType);
						} else {
							_session.Logger.Warn("This cannot happen");
						}
						newNode.Parent = _parent;
						_parent.Children.Add(newNode);
						result.Add(newNode);
					}
				}
				_resultCallback(_session, _parent, result);
			}
			_session.Logger.Debug("End GetChildrenCommand");
		}
	}
}
